class SoftLabel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            operationProInfo: '',
            list: [''],
        };
        this.listSize = 0;
        this.pageCount = 1;
        this.dateMatch = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
        this.unitAliasData = {};
        this.unitsNum = {};
        this.unitsFloorNum = {};
        this.unitsRoomNum = {};
    }

    componentDidMount() {
        this.verify = {
            normalDate: (value) => {
                if (this.refs.isPay.value === '1' && !value) {
                    return '必须选择缴费时间!';
                }
            }
        };
    }

    /* custom functions */
    updateList(page, pageSize) {
        let params = {};
        params.page = page;
        params.pageSize = pageSize;
        params.commCode = this.refs.buildingSelectList.commCode;
        params.buildingCode = this.refs.buildingSelectList.buildingCode;
        params.unitCode = this.refs.buildingSelectList.unitCode;
        params.floorCode = this.refs.buildingSelectList.floorCode;
        postJson("/property/fee/queryPropertyFeePage.x", params, (data) => {
            console.log("data", data);
            let list = data.data.list;
            this.pageCount = page;
            this.listSize = data.data.size;
            this.setState({
                list: list
            });
        })
    }

    search() {
        this.updateList(1, 10);
    }

    addLabel() {
        let commCode = this.refs.buildingSelectList.commCode;
        if (!commCode) {
            layui.layer.msg("请选择小区");
            return;
        }

        layui.layer.confirm('确定要创建这个小区的物业缴费信息吗?创建后app就可以在手机上看到缴费信息。', (index) => {
            postJson("/property/fee/createPropertyFee.x", {
                commCode: commCode
            }, () => {
                layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;创建成功', {icon: 6});
                this.updateList(1, 10);
            });
            layui.layer.close(index);
        });
    }

    /**
     * 导入excel表
     * 使用SheetJs将excel文件转换成json数组上传
     */
    importExcel() {
        let commCode = this.refs.buildingSelectList.commCode;
        if (!commCode) {
            layui.layer.msg("请选择小区");
            return;
        }


        let params = {commCode: commCode};

        postJson("/building/getUnitsInfoForExport.x", $.param(params), (data) => {
            let buildings = data.data;
            /* 将楼栋与别名的映射关系转成map */
            for (let i = 0; i < buildings.length; i++) {
                /* 楼栋与别名的映射关系 */
                this.unitAliasData[buildings[i].areaName] = buildings[i].areaAliasName;

                /* 每个楼栋最大的单元数 */
                if (!this.unitsNum[buildings[i].areaName] || parseInt(this.unitsNum[buildings[i].areaName]) < parseInt(buildings[i].unitName))
                    this.unitsNum[buildings[i].areaName] = buildings[i].unitName;

                /* 每个单元最大的楼层数 */
                this.unitsFloorNum[buildings[i].areaName + '-' + buildings[i].unitName] = buildings[i].floorNum;
                /* 每个单元最大房间数 */
                this.unitsRoomNum[buildings[i].areaName + '-' + buildings[i].unitName] = buildings[i].roomNum;
            }
        });
        this.refs.import.importExcel();
    }

    dataCheck(line, tempArr) {
        if (tempArr[0].length !== 8) {
            layui.layer.alert("第" + line + "行数据" + tempArr[0] + "错误<br>范例:01010101(含义:01栋01单元01楼01号房)", {title: "格式不对"});
            return false;
        } else if (isNaN(parseFloat(tempArr[1]))) {
            layui.layer.alert("第" + line + "行数据" + tempArr[1] + "错误<br>物业费错误", {title: "格式不对"});
            return false;
        } else if (!this.dateMatch.test(tempArr[2])) {
            layui.layer.alert("第" + line + "行数据" + tempArr[2] + "错误<br>日期格式：yyyy-mm-dd 如：2008-08-08", {title: "格式不对"});
            return false;
        } else if (!/^\d+$/.test(tempArr[3])) {
            layui.layer.alert("第" + line + "行数据" + tempArr[3] + "错误<br>月数填写错误", {title: "格式不对"});
            return false;
        } else
            return true;
    }

    buildingCheck(area, unit, floor, room, buildingStr) {
        if (!this.unitAliasData.hasOwnProperty(parseInt(area) + '')) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + area + "楼栋不存在!");
            return false;
        }
        if (parseInt(unit) > this.unitsNum[parseInt(area) + '']) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + unit + "单元不存在!");
            return false;
        }
        if (parseInt(floor) > this.unitsFloorNum[parseInt(area) + '-' + parseInt(unit)]) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + floor + "楼层不存在! 该单元最高" + this.unitsFloorNum[parseInt(area) + '-' + parseInt(unit)] + "层!");
            return false;
        }
        if (parseInt(room) > this.unitsRoomNum[parseInt(area) + '-' + parseInt(unit)]) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + room + "房号不存在!<br>该单元楼层最大房号数目" + this.unitsRoomNum[parseInt(area) + '-' + parseInt(unit)]);
            return false;
        }
        return true;
    }

    importDataHandle(data) {
        let titleArr = data[0];
        if (titleArr[0] !== '楼栋编号' || titleArr[1] !== '物业费' || titleArr[2] !== '账单日期' || titleArr[3] !== '缴费月数') {
            layui.layer.alert("excel表单第一行三个字段的值必须是<br>业主楼栋编号、物业费、账单日期、缴费月数", {title: "格式不对"});
            return;
        }

        let uploadArr = [];
        for (let i = 1; i < data.length; i++) {
            let tempArr = data[i];

            if (tempArr.length === 0)
                continue;

            if (!this.dataCheck(i + 1, tempArr))
                return;

            let areaName = tempArr[0].substr(0, 2);
            let unitName = tempArr[0].substr(2, 2);
            let floor = tempArr[0].substr(4, 2);
            let room = tempArr[0].substr(6, 2);

            if (!this.buildingCheck(areaName, unitName, floor, room, tempArr[2]))
                return;

            let commCode = $.trim(this.refs.buildingSelectList.commCode);
            let propertyFeeInfo = {
                id: commCode + tempArr[0],
                fee: tempArr[1],
                currentBillDate: tempArr[2],
                months: tempArr[3],
                isPay: 0,
                commCode: commCode
            };

            uploadArr.push(propertyFeeInfo);
        }

        console.log("uploadArr", uploadArr);
        layui.layer.confirm("确定导入此" + uploadArr.length + "条数据么?", () => {
            postRJson("/property/fee/saveBatchsPropertyFee.x", JSON.stringify(uploadArr), (data) => {
                layui.layer.alert(data.data, (index) => {
                    this.refs.import.clearData();
                    layui.layer.close(index);
                });
            });
        });
    }

    /**
     * 将json对象数组转换成二维数组，因为对象中的key对excel来说是没有意义的
     * 如果直接传入对象数组，会造成浏览器卡死!
     * @returns {Array}
     */
    ownerJsonObj2JsonArray(propertyFeeInfos) {
        console.log("---------------->    ", propertyFeeInfos);
        let retArray = [];
        let titleArr = ['楼栋编号', '物业费', '账单日期', '缴费月数', '缴费账单日期', '是否缴费'];
        retArray.push(titleArr);
        for (let i = 0; i < propertyFeeInfos.length; i++) {
            let tempArr = [];
            tempArr.push(propertyFeeInfos[i].buildingCode + propertyFeeInfos[i].unitCode + propertyFeeInfos[i].floorCode + propertyFeeInfos[i].roomCode);
            tempArr.push(propertyFeeInfos[i].fee);
            tempArr.push(propertyFeeInfos[i].currentBillDate);
            tempArr.push(propertyFeeInfos[i].months);
            tempArr.push(propertyFeeInfos[i].lastBillDate);
            tempArr.push(propertyFeeInfos[i].isPay === 1 ? '已缴费' : '未交费');
            retArray.push(tempArr);
        }

        return retArray;
    }

    /**
     * 导出excel表
     * 用到SheetJs，纯前端转换成excel文件
     */
    exportExcel() {
        let commCode = this.refs.buildingSelectList.commCode;
        if (!commCode) {
            layui.layer.msg("请选择小区");
            return;
        }

        let confirmStr = "确认要导出【" + this.refs.buildingSelectList.commName + "】物业缴费数据么?";

        layui.layer.confirm(confirmStr, (index) => {
            let params = {};
            params.commCode = commCode;
            this.refs.export.exportExcel("/property/fee/getPropertyFeesForExport.x", params, this.ownerJsonObj2JsonArray);
            layui.layer.close(index);
        });
    }

    goHelp() {
        window.location.href = "/api/v3/cms/anon/getContent?ueditorId=help_property_fee_params&template=UecontentWebWithFrame";
    }

    resetStateSubmit() {
        postJson("/property/fee/resetState.x", {
            id: this.state.operationProInfo.id,
            isPay: this.refs.isPay.value,
            lastBillDate: this.refs.normalDate ? this.refs.normalDate.value : '',
            commCode: this.state.operationProInfo.commCode
        }, () => {
            layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;设置成功', {icon: 6});
            this.updateList(this.pageCount, 10);
            this.refs.modal_reset_state.close();
        });
    }

    callPropertyFee() {
        let commCode = this.refs.buildingSelectList.commCode;
        if (!commCode) {
            layui.layer.msg("请选择小区");
            return;
        }
        postJson("/property/fee/callPropertyFee.x", {
            commCode: commCode
        }, () => {
            layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;催促成功', {icon: 6});
        });
    }

    resetState(proInfo) {
        this.state.operationProInfo = proInfo;
        this.refs.modal_reset_state.show();
    }

    render() {
        return (
            <Frame header="物业缴费信息" headerBtns={[
                <HeaderBtn onClick={() => this.goHelp()}><i className="fa fa-question-circle-o"
                                                            style={{fontSize: 16}}/>&nbsp;帮助文档</HeaderBtn>,
                <HeaderBtn onClick={() => this.addLabel()}><i className="fa fa-plus"/>&nbsp;生成账单</HeaderBtn>,
                <HeaderBtn onClick={() => this.callPropertyFee()}><i className="fa fa-volume-control-phone"/>&nbsp;催促缴费</HeaderBtn>
            ]
            }
            >
                <Form type="pane">
                    <Item>
                        <LayuiCommSelect
                            formLabelName="小区选择"
                            mask={['room']}
                            ref="buildingSelectList"
                            onChangeComm={() => this.updateList(1, 10)}
                            onChangeBuilding={() => this.updateList(1, 10)}
                            onChangeUnit={() => this.updateList(1, 10)}
                            onChangeFloor={() => this.updateList(1, 10)}/>
                    </Item>
                    <Table ref="table" count={this.listSize}
                           pageOnClick={(page, pageSize) => this.updateList(page, pageSize)}
                           toolbar={[
                               <FileImportButton
                                   ref="import"
                                   onClick={() => this.importExcel()}
                                   dataCallBack={(data) => this.importDataHandle(data)}
                               >Excel导入
                               </FileImportButton>,
                               <FileExportButton
                                   ref="export"
                                   exportFileName="物业缴费信息表"
                                   onClick={() => this.exportExcel()}
                               >导出
                               </FileExportButton>]
                           }>
                        <thead>
                        <tr>
                            <th>小区名</th>
                            <th>楼栋号</th>
                            <th>单元号</th>
                            <th>房号</th>
                            <th>物业费</th>
                            <th>是否缴费</th>
                            <th>最近账单缴费时间</th>
                            <th width="60">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {

                            this.state.list.map((proInfo) => {
                                return <tr>
                                    <td>{proInfo.commName}</td>
                                    <td>{proInfo.buildingAliasName}</td>
                                    <td>{proInfo.unitAliasName}</td>
                                    <td>{proInfo.floorCode + proInfo.roomCode}</td>
                                    <td>{proInfo.fee}</td>
                                    <td>{proInfo.isPay === 1 ? <div style={{color: 'blue'}}>已缴费</div> :
                                        <div style={{color: 'red'}}>未缴费</div>}</td>
                                    <td>{proInfo.lastBillDate}</td>
                                    <td>
                                        <Button btnType="normal" size="xs"
                                                onClick={() => this.resetState(proInfo)}>状态重置</Button>
                                    </td>
                                </tr>
                            })
                        }
                        </tbody>
                    </Table>

                    <Modal title="状态重置" ref="modal_reset_state">
                        <Form type="pane"
                              size="sm"
                              verify={() => {
                                  return this.verify;
                              }}>
                            <Item>
                                <Label>是否缴费</Label>
                                <Select ref="isPay"
                                        onChange={() => this.setState({})}>
                                    <option value="1">已缴费</option>
                                    <option value="0">未交费</option>
                                </Select>
                            </Item>
                            <Item>
                                <Label>缴费时间</Label>
                                <DateSelect placeHolder={this.refs.isPay && this.refs.isPay.value === '1' ? "账单缴费时间" : '上次账单缴费时间'}
                                            ref="normalDate" lay-verify="normalDate"/>
                            </Item>
                            <Item>
                                <Button formBtn={true}
                                        size='sm'
                                        btnType='normal'
                                        lay-submit="true"
                                        onClick={() => this.resetStateSubmit()}>确定重置</Button>
                            </Item>
                        </Form>
                    </Modal>
                </Form>
            </Frame>
        )
    }
}

ReactDOM.render(<SoftLabel/>, document.getElementById('root'));
